<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :class-name="'sub-navbar '+ 'draft'">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="createApiReview(1)">发布
        </el-button>
        <el-button v-loading="loading" type="warning" @click="createApiReview(0)">草稿</el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>

          <Warning />

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="apiName">
              <MDinput v-model="postForm.apiName" :maxlength="100" name="name" required>
                Api名
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="75px" label="请求方式:" class="postInfo-container-item">
                    <el-select v-model="postForm.apiMethod" placeholder="请求方式">
                      <el-option v-for="item in methodOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="60px" label="编写人:" class="postInfo-container-item" prop="user">
                    <el-select v-model="postForm.userId" :remote-method="getSelectUserList" filterable remote placeholder="搜索用户">
                      <el-option v-for="item in userListOptions" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="68px" label="api描述:">
          <el-input :rows="1" v-model="postForm.apiDescription" type="textarea" class="article-textarea" autosize placeholder="请输入接口中文名"/>
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
        </el-form-item>

        <el-form-item prop="apiContent" style="margin-bottom: 30px;">
          <Tinymce ref="editor" :height="400" v-model="postForm.apiContent" />
        </el-form-item>

        <!-- <el-form-item prop="content" style="margin-bottom: 30px;">
          <div class="editor-container">
            <json-editor ref="jsonEditor" v-model="jsonValue"/>
          </div>
        </el-form-item> -->

      </div>
    </el-form>

  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/singleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
// import { fetchArticle } from '@/api/article'
import Warning from './Warning'
import JsonEditor from '@/components/JsonEditor'
import { saveApiReview, fetchDetail } from '@/api/project/apiReview'
import { fetchSelectUserList } from '@/api/user/user'
import { fetchApiMethodOptions } from '@/enums/ApiMethodEnum'
// import { fetchApiStatusKeyValue } from '@/enums/apiStatusEnum'

const defaultForm = {
  id: 0,
  apiName: '', // 接口英文名
  apiDescription: '', // 接口中文名
  apiContent: '接口设计', // 接口请求体和返回体
  apiStatus: undefined,
  apiMethod: 0,
  userId: 1,
  projectId: 1
}
const methodOptions = fetchApiMethodOptions()

// const statusKeyValue = fetchApiStatusKeyValue(statusOptions)

export default {
  name: 'ApiReviewDetail',
  components: { Tinymce, MDinput, Upload, Sticky, Warning, JsonEditor },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        apiName: [{ validator: validateRequire }],
        apiDescription: [{ validator: validateRequire }],
        apiContent: [{ validator: validateRequire }],
        user: [{ validator: validateRequire }],
        apiMethod: [{ validator: validateRequire }]
      },
      tempRoute: {},
      methodOptions,
      listQuery: {
        userName: ''
      }
      // jsonValue: JSON.parse('[{}]')
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.apiContent.length
    },
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      // this.fetchData(id)
      this.getDetail(id)
    } else {
      console.log(this.postForm)
      this.postForm = Object.assign({}, defaultForm)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    // fetchData(id) {
    //   fetchArticle(id).then(response => {
    //     this.postForm = response.data
    //     // Just for test
    //     this.postForm.title += `   Article Id:${this.postForm.id}`
    //     this.postForm.content_short += `   Article Id:${this.postForm.id}`

    //     // Set tagsview title
    //     this.setTagsViewTitle()
    //   }).catch(err => {
    //     console.log(err)
    //   })
    // },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑接口' : 'Edit API'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('updateVisitedView', route)
    },
    createApiReview(status) {
      this.postForm.apiStatus = status
      this.$refs.postForm.validate(valid => {
        if (valid) {
          saveApiReview(this.postForm).then(response => {
            this.loading = true
            this.$notify({
              title: '成功',
              message: '发布文章成功',
              type: 'success',
              duration: 2000
            })
            this.postForm = Object.assign(this.postForm, defaultForm)
            this.loading = false
            this.$router.push({ path: '/project/apireviewlist' })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getSelectUserList(query) {
      this.listQuery.userName = query
      fetchSelectUserList(this.listQuery).then(response => {
        this.userListOptions = response.data.data.list
        this.listQuery.userName = ''
      })
    },
    getDetail(id) {
      // TODO 用get请求的话，用之前在controller设置的方法就过不了跨域了
      fetchDetail(id).then(response => {
        this.postForm = response.data.data
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
  .editor-container{
    position: relative;
    height: 100%;
    line-height: 1.15;
  }
}
</style>
